<template>
	<view class="page" style="">
		<commonNav :currentSewLine="currentSewLine.sewingName" :navTitle="navTitle" @backRouter="backToLog" />
		<view class="form">
			<!-- 单号 款名 款号 客户 颜色 尺码 -->
			<u--form labelPosition="top" :model="formData" :rules="rules" ref="from1">
				<u-form-item :label="$t('pages.quality.productionNo')" prop="productionInfo.billNo" borderBottom ref="item1">
					<!-- <view @click="changeShow = true"> -->
					<u--input v-model="formData.productionInfo.billNo" border="none" disabled>
					</u--input>
					<!-- </view> -->
				</u-form-item>
				<u-form-item :label="$t('pages.quality.styleName')" prop="productionInfo.styleName" borderBottom ref="item1" style="width: 30%;">
					<u--input v-model="formData.productionInfo.styleName" border="none" disabled></u--input>
				</u-form-item>
				<u-form-item :label="$t('pages.quality.styleNo')" prop="productionInfo.styleNo" borderBottom ref="item1">
					<u--input v-model="formData.productionInfo.styleNo" border="none" disabled></u--input>
				</u-form-item>
				<u-form-item :label="$t('pages.quality.customer')" prop="productionInfo.customerName" borderBottom ref="item1">
					<u--input v-model="formData.productionInfo.customerName" border="none" disabled></u--input>
				</u-form-item>
				<u-form-item :label="$t('pages.quality.color')" prop="productionInfo.color" borderBottom ref="itemColor">
					<view @click="commonShow.colorShow = true">
						<u--input v-model="formData.productionInfo.color" type="select" border="none" readonly
							:disabled="allowEdit"></u--input>
					</view>
				</u-form-item>
				<u-form-item :label="$t('pages.quality.size')" prop="productionInfo.size" borderBottom ref="itemSize">
					<view @click="commonShow.sizeShow = true">
						<u--input v-model="formData.productionInfo.size" border="none" readonly :disabled="allowEdit">
						</u--input>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<view class="statistics">
			<view class="number">
				<view class="number-title">{{ $t('pages.quality.pass') }}</view>
				<u-number-box v-model="formData.productionInfo.qualifiedNum" integer :min="0">
					<view slot="minus" class="minus flex-center">
						——
					</view>
					<u--input slot="input" v-model="formData.productionInfo.qualifiedNum" type="number"
						@input="TypeInput($event, 'qualifiedNum')" :disabled="allowEdit" class="input flex-center">
					</u--input>
					<view slot="plus" class="plus flex-center">
						+
					</view>
				</u-number-box>
			</view>
			<view class="number">
				<view class="number-title">{{ $t('pages.quality.rework') }}</view>
				<u-number-box v-model="formData.productionInfo.unqualifiedNum" integer :min="0">
					<view slot="minus" class="minus flex-center">
						——
					</view>
					<u--input slot="input" v-model="formData.productionInfo.unqualifiedNum" type="number"
						@input="TypeInput($event, 'unqualifiedNum')" :disabled="allowEdit" class="input flex-center">
					</u--input>
					<view slot="plus" class="plus flex-center">
						+
					</view>
				</u-number-box>
			</view>
			<view class="number">
				<view class="number-title">{{ $t('pages.quality.scarp') }}</view>
				<u-number-box v-model="formData.productionInfo.discardedNum" integer :min="0">
					<view slot="minus" class="minus flex-center">
						——
					</view>
					<u--input slot="input" v-model="formData.productionInfo.discardedNum" type="number"
						@input="TypeInput($event, 'discardedNum')" :disabled="allowEdit" class="input flex-center">
					</u--input>
					<view slot="plus" class="plus flex-center">
						+
					</view>
				</u-number-box>
			</view>
		</view>
		<view class="add-defect">
			<u-button type="primary" @click="addDefect">{{ $t('common.add') }}</u-button>
			<!-- <u-button type="primary" @click="addProcess">新增问题工序</u-button> -->
		</view>
		<view class="table">
			<uni-table :stripe="true" :emptyText="$t('common.noData')">
				<!-- 表头行 -->
				<uni-tr style="background: #E8E8E8;">
					<uni-th width="50px" align="center">{{ $t('pages.quality.no') }}</uni-th>
					<uni-th width="100px" align="center">{{ $t('pages.quality.type') }}</uni-th>
					<uni-th width="100px" align="center">{{ $t('pages.quality.content') }}</uni-th>
					<uni-th width="80px" align="center">{{ $t('pages.quality.pieces') }}</uni-th>
					<uni-th width="60px" align="center">{{ $t('common.operate') }}</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item, index) in formData.productionInfo.inspectionDetailList" :key="index">
					<uni-td align="center">{{index + 1}}</uni-td>
					<uni-td align="center">
						<view class="td-select" @click.stop="getCurrentRowInfo(item)">
							<uni-icons type="bottom" color="#ccc" size="20"></uni-icons>
							{{ item.type ? $t('pages.quality.probProcess') : $t('pages.quality.defects') }}
						</view>
						<view v-if="false">{{ item.unqualifiedProcess }}</view>
					</uni-td>
					<uni-td align="center">
						<!-- <view class="td-select" @click.stop="getCurrentRowInfoDetail(item)">
							<uni-icons type="bottom" color="#ccc" size="20"></uni-icons>
							{{ item.type ? item.unqualifiedProcess : item.unqualifiedReason }}
						</view> -->
						<view v-if="item.type" class="td-select" @click.stop="getCurrentRowInfoDetail(item)">
							<uni-icons type="bottom" color="#ccc" size="20"></uni-icons>
							{{ item.unqualifiedProcess }}
						</view>
						<!-- <view v-if="!item.type" class="td-select" @click.stop="getCurrentRowInfoDetail(item)">
							<uni-icons type="bottom" color="#ccc" size="20"></uni-icons>
							{{ item.unqualifiedReason }}
						</view> -->
						<uni-data-picker 
							v-if="!item.type"
							:localdata="treeData" 
							v-model="item.defectiveId"
							@change="e => onDefectChange(e, item)"
							style="font-size: 20px;"
							:map="{text: 'defectiveSpot', value: 'id'}"
						></uni-data-picker>
						<view v-if="false">{{ item.unqualifiedReason }}</view>
					</uni-td>
					<uni-td align="center">
						<view>
							<u--input v-model="item.num" type="number" class="td-input flex-center"></u--input>
						</view>
					</uni-td>
					<uni-td align="center">
						<view class="td-handle">
							<!-- 	<i class="t-icon t-icon-zengjiatianjiajiahao"
								@click="addItem(item, index)"></i> -->
							<image src="../../../static/img/public/add.png" style="width: 37.523rpx;height: 37.523rpx;"
								@click="addItem(item, index)"></image>
							<i class="t-icon t-icon-shanchu" @click="delItem(item, index)"></i>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<!-- <u-button @click="openDialog">点击</u-button> -->
		<view class="fixed-button">
			<view class="back">
				<u-button @click="backRouter">{{ $t('common.return') }}</u-button>
			</view>
			<view class="submit">
				<u-button type="primary" :disabled="!allowClick" @click="updateProductionInfo">{{ $t('common.submit') }}</u-button>
			</view>
		</view>
		<!-- 弹出窗 -->
		<styleSelect ref="styleSelect" @selectStyle="getNewStyleInfo" />
		<!-- 瑕疵点和问题工序类型选择窗 -->
		<u-picker :show="customShow" :columns="customType" @cancel="customShow = false" @confirm="confirmCustomType"
			keyName="text" :cancelText="$t('common.cancel')" :confirmText="$t('common.complete')"></u-picker>
		<!-- 颜色选择窗 -->
		<u-picker :show="commonShow.colorShow" :columns="columnsColor" @cancel="commonShow.colorShow = false"
			@confirm="confirmColor" keyName="color" :cancelText="$t('common.cancel')"
			:confirmText="$t('common.complete')"></u-picker>
		<!-- 尺码选择窗 -->
		<u-picker :show="commonShow.sizeShow" :columns="columnsSize" @cancel="commonShow.sizeShow = false"
			@confirm="confirmSize" keyName="size" :cancelText="$t('common.cancel')"
			:confirmText="$t('common.complete')"></u-picker>
		<!-- 类型选择窗 -->
		<u-picker :show="commonShow.typeShow" :columns="columnsType" @cancel="commonShow.typeShow = false"
			@confirm="confirmType" keyName="defectiveSpot" :cancelText="$t('common.cancel')"
			:confirmText="$t('common.complete')"></u-picker>
		<!-- 内容选择框 -->
		<u-picker :show="commonShow.contentShow" :columns="columnsContent" @cancel="commonShow.contentShow = false"
			@confirm="confirmContent" keyName="processName" :cancelText="$t('common.cancel')"
			:confirmText="$t('common.complete')"></u-picker>
		<!-- 删除提示 -->
		<u-modal :show="delShow" :confirmText="$t('common.determine')" :cancelText="$t('common.cancel')"
			:showCancelButton="true" @confirm="del" @cancel="delShow = false" :content="$t('pages.quality.tips4')"></u-modal>
		<!-- 换单提示 -->
		<u-modal :show="changeShow" :confirmText="$t('common.determine')" :cancelText="$t('common.cancel')"
			:showCancelButton="true" @confirm="changeProduction" @cancel="changeShow = false" :content="$t('pages.quality.tips5')">
		</u-modal>
	</view>
</template>

<script>
	import storage from "@/utils/storage.js"
	import styleSelect from "@/components/production/styleSelect.vue"
	import commonNav from "@/components/nav/commonNav.vue"
	import {
		isPositiveInteger
	} from "@/utils/verify.js"
	import {
		getRegistrationLog
	} from "@/api/production.js"
	import {
		getSizeAndColor,
		getDefectiveSpotList,
		getProductionDetailList,
		saveRegistrationLog,
		getDefectiveSpotTree
	} from "@/api/recordUpate.js"
	import { findTreeNode } from '@/utils/findTreeNode'
	export default {
		components: {
			styleSelect,
			commonNav
		},
		data() {
			return {
				treeData: [],
				navTitle: this.$t('home.qualityRecordEdit'),
				productionId: '',
				allowClick: true,
				commonShow: {
					colorShow: false,
					sizeShow: false,
					typeShow: false,
					contentShow: false
				},
				customShow: false,
				customType: [
					[{
							code: 0,
							text: this.$t('pages.quality.defects')
						},
						{
							code: 1,
							text: this.$t('pages.quality.probProcess')
						},
					]
				],
				columnsColor: [
					[]
				],
				columnsSize: [
					[]
				],
				// 瑕疵点内容
				columnsType: [
					[]
				],
				// 问题工序内容
				columnsContent: [
					[]
				],
				changeShow: false,
				delShow: false,
				// 被删除内容
				delItemContent: {},
				delItemIndex: 0,
				queryParams: {
					sewingId: '',
					// today: 0,
					inspectionId: ''
				},
				allowEdit: true,
				currentRowInfo: '',
				currentSewLine: storage.get('currentSewLineInfo') || {
					sewingName: '未选择缝制线'
				},
				formData: {
					productionInfo: {
						name: '',
						billNo: '',
						styleName: '',
						color: '',
						size: '',
						styleNo: ''
					},
				},
				rules: {
					'productionInfo.size': {
						type: 'string',
						required: true,
						message: this.$t('pages.quality.validate1'),
						trigger: ['blur', 'change']
					},
					'productionInfo.color': {
						type: 'string',
						required: true,
						message: this.$t('pages.quality.validate2'),
						trigger: ['blur', 'change']
					},
				},
			};
		},
		computed: {
			// 报废+返工数量
			defectTotal() {
				return Number(this.formData.productionInfo.discardedNum) + Number(this.formData.productionInfo
					.unqualifiedNum)
			},
		},
		onShow() {},
		onLoad(option) {
			this.queryParams.inspectionId = option.id
			this.queryParams.sewingId = option.sewingId
			this.productionId = option.productionId
			if (option.type === 'update') this.allowEdit = false
		},
		mounted() {
			this.getDefectiveSpotListInfo()
			this.getProductionDetailListInfo()
			this.getSizeAndColorInfo()
			setTimeout(() => {
				this.getRegistrationLogInfoByOne()
			}, 50)
		},
		methods: {
			backToLog() {
				uni.navigateTo({
					url: `/pages/quality/production/productionRecord?sewingId=${this.queryParams.sewingId}&type='refresh'`
				})
			},
			addDefect() {
				let defectObj = {
					type: 0,
					productionId: this.productionId,
					styleId: this.formData.productionInfo.styleId,
					inspectionId: this.queryParams.inspectionId,
					sewingId: this.queryParams.sewingId
				}
				if (!this.formData.productionInfo.inspectionDetailList || !this.formData.productionInfo
					.inspectionDetailList.length) {
					this.formData.productionInfo.inspectionDetailList = []
					this.formData.productionInfo.inspectionDetailList.push(defectObj)
					uni.$u.toast(this.$t('pages.quality.addSuccess'))
				} else {
					this.formData.productionInfo.inspectionDetailList.push(
						defectObj
					)
					uni.$u.toast(this.$t('pages.quality.addSuccess'))
				}
			},
			TypeInput(e, type) {
				// 只能输入数字的验证;
				const inputType = /[^\d]/g //想限制什么类型在这里换换正则就可以了
				this.$nextTick(function() {
					if (type === 'qualifiedNum') {
						this.formData.productionInfo.qualifiedNum = e.replace(inputType, '');
					} else if (type === 'unqualifiedNum') {
						this.formData.productionInfo.unqualifiedNum = e.replace(inputType, '');
					} else {
						this.formData.productionInfo.discardedNum = e.replace(inputType, '');
					}

				})
			},
			// 获取单条记录信息
			getRegistrationLogInfoByOne() {
				getRegistrationLog(this.queryParams).then(res => {
					if (res.code !== 0) return uni.$u.toast(res.msg)
					this.formData.productionInfo = res.data.list[0]
					try {
						this.formData.productionInfo.inspectionDetailList.forEach(item => {
							const targetTreeNode = findTreeNode(this.treeData, item.unqualifiedReason, 'defectiveSpot')
							if (targetTreeNode) {
								item.defectiveId = targetTreeNode?.id
							} else {
								item.defectiveId = item.unqualifiedReason
								this.treeData.push({
									defectiveSpot: item.unqualifiedReason,
									id: item.unqualifiedReason
								})
							}
						})
					} catch (error) {
						console.log(error);
					}
				})
			},
			// 获取瑕疵点类型
			async getDefectiveSpotListInfo() {
				getDefectiveSpotList().then(res => {
					if (res.code !== 0) return uni.$u.toast(res.msg)
					res.data.map(item => {
						this.columnsType[0].push(item)
					})
				})

				const res = await getDefectiveSpotTree({})
				this.treeData = res.data
			},
			// 获取工序内容
			async getProductionDetailListInfo() {
				getProductionDetailList({
					productionId: this.productionId
				}).then(res => {
					if (res.code !== 0) return uni.$u.toast(res.msg)
					res.data.map(item => {
						this.columnsContent[0].push(item)
					})
				})
			},
			// 获取颜色和尺码
			getSizeAndColorInfo() {
				getSizeAndColor({
					productionId: this.productionId
				}).then(res => {
					if (res.code !== 0) return uni.$u.toast(res.msg)
					let colorArr = Object.keys(res.data.colorList)
					let sizeArr = Object.keys(res.data.sizeList)
					colorArr.map(item => {
						this.columnsColor[0].push({
							color: item
						})
					})
					sizeArr.map(item => {
						this.columnsSize[0].push({
							size: item
						})
					})
				})
			},
			//切换生产单
			changeProduction() {
				this.changeShow = false
				this.$refs.styleSelect.open()
			},
			getNewStyleInfo(e) {
				this.formData.productionId = e.productionId
				this.formData.productionInfo.styleNo = e.styleNo
				this.formData.productionInfo.billNo = e.billNo
				this.formData.productionInfo.styleName = e.styleName
				this.formData.productionInfo.customerName = e.customerName
				this.formData.productionInfo.color = ''
				this.formData.productionInfo.size = ''
				this.columnsColor[0] = []
				this.columnsSize[0] = []
				this.getProductionDetailListInfo()
				this.getSizeAndColorInfo()
			},
			// 新增表格行
			addItem(item, index) {
				let addObj = {
					type: item.type,
					productionId: item.productionId,
					styleId: item.styleId,
					inspectionId: item.inspectionId,
					sewingId: item.sewingId
				}
				this.formData.productionInfo.inspectionDetailList.splice(index + 1, 0, addObj)
			},
			// 删除表格行
			delItem(item, index) {
				this.delItemContent = item
				this.delItemIndex = index
				this.delShow = true
			},
			del() {
				this.formData.productionInfo.inspectionDetailList.splice(this.delItemIndex, 1)
				this.delShow = false
				uni.$u.toast(this.$t('common.deleteTheSuccess'))
			},
			backRouter() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 保存修改
			updateProductionInfo() {
				this.$refs.from1.validate().then(res => {
					if (!Number(this.formData.productionInfo.qualifiedNum) && !Number(this.formData.productionInfo.unqualifiedNum) && !Number(this.formData.productionInfo.discardedNum)) {
						return uni.$u.toast(this.$t('pages.quality.tips0'))
					}
					// 校验
					let dfectArr = []
					let processArr = []
					if (this.formData.productionInfo.inspectionDetailList && this.formData.productionInfo
						.inspectionDetailList.length > 0) {
						this.formData.productionInfo.inspectionDetailList.forEach(item => {
							if (item.type) {
								processArr.push(item.unqualifiedProcess)
							} else {
								dfectArr.push(item.unqualifiedReason)
							}
						})
						// 限制内容不能为空
						for (let proItem of processArr) {
							if (!proItem) return uni.$u.toast(this.$t('pages.quality.tips10'))
						}
						for (let defcItem of dfectArr) {
							if (!defcItem) return uni.$u.toast(this.$t('pages.quality.tips11'))
						}
						if (Array.from(new Set(processArr)).length < processArr.length) return uni.$u.toast(this.$t('pages.quality.tips6'))
						if (Array.from(new Set(dfectArr)).length < dfectArr.length) return uni.$u.toast(this.$t('pages.quality.tips7'))
						for (let it of this.formData.productionInfo.inspectionDetailList) {
							if (it.num && !isPositiveInteger(it.num)) return uni.$u.toast(this.$t('pages.quality.tips8'))
							if (it.num > this.defectTotal) return uni.$u.toast(this.$t('pages.quality.tips9'))
						}
					}

					this.allowClick = false
					this.formData.productionInfo.sewingId = this.queryParams.sewingId
					saveRegistrationLog(this.formData.productionInfo).then(res => {
						if (res.code !== 0) {
							this.allowClick = false
							return uni.$u.toast(res.msg)
						}
						uni.$u.toast(this.$t('common.success'))
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/quality/production/productionRecord?sewingId=${this.queryParams.sewingId}&type='refresh'`
							})
							this.allowClick = true
						}, 2000)
					})
				})
			},
			openDialog() {
				this.$refs.styleSelect.open()
			},
			confirmColor(e) {
				this.formData.productionInfo.color = e.value[0].color
				this.commonShow.colorShow = false
			},
			confirmSize(e) {
				this.formData.productionInfo.size = e.value[0].size
				this.commonShow.sizeShow = false
			},
			confirmType(e) {
				this.currentRowInfo.unqualifiedReason = e.value[0].defectiveSpot
				this.commonShow.typeShow = false
			},
			confirmContent(e) {
				this.currentRowInfo.unqualifiedProcess = e.value[0].processName
				this.commonShow.contentShow = false
			},
			confirmCustomType(e) {
				this.currentRowInfo.type = e.value[0].code
				this.customShow = false
			},
			// 获取当前被选择的行数据
			getCurrentRowInfo(item) {
				if (this.allowEdit) return false
				this.currentRowInfo = item
				this.customShow = true
			},
			getCurrentRowInfoDetail(item) {
				if (this.allowEdit) return false
				this.currentRowInfo = item
				item.type ? this.commonShow.contentShow = true : this.commonShow.typeShow = true
			},
			onDefectChange(e, item) {
				const value = e.detail.value
				if (value.length) {
					item.unqualifiedReason = value?.[value.length - 1]?.text
				}
			
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		width: 100%;
		// height: 100vh;
	}

	.form {
		padding-top: 5%;
	}

	.u-form {
		display: flex;
		flex-wrap: wrap;
		font-size: 1rem;
	}

	.u-form-item {
		width: 20%;
		margin: 1% 1%;
	}

	/deep/ .u-form-item__body__left {
		width: 938.086rpx !important;
	}
	/deep/ .u-form-item__body__left__content__label {
		font-size: 1rem;
	}

	/deep/ .uni-input-input {
		font-size: 1rem;
	}

	.statistics {
		display: flex;

		.number {
			width: 30%;
			margin-left: 2%;
			font-size: 1.2rem;
			display: flex;
			align-items: center;
		}
	}

	.add-defect {
		width: 10%;
		margin-top: 2%;
		position: absolute;
		right: 4%;
		// button {
		// 	margin: 0 2%;
		// }
	}

	.u-number-box {
		width: 70%;
		height: 100%;
	}

	.number-title {
		width: 30%;
	}

	.minus {
		width: 75.047rpx;
		height: 75.047rpx;
		border-radius: 4px;
		opacity: 1;
		box-sizing: border-box;
		border: 2px solid #3E8FF7;
		font-size: 1rem;
		font-weight: bold;
		color: #3E8FF7;
	}

	.plus {
		width: 75.047rpx;
		height: 75.047rpx;
		padding-bottom: 9.381rpx;
		border-radius: 4px;
		opacity: 1;
		box-sizing: border-box;
		border: 2px solid #3E8FF7;
		font-size: 2.5rem;
		font-weight: 100;
		color: #3E8FF7;
	}

	.input {
		width: 100%;
		height: 100%;
		border-radius: 7.505rpx;
		border: 1px solid #DDDDDD;
		margin: 0 4%;
		font-size: 1.5rem;
		background-color: #FFFFFF;
	}

	.table {
		padding-bottom: 7%;
		margin-top: 6%;
		height: 440rpx;
		overflow-y: auto;

		/deep/ .uni-table-th-content {
			font-size: 1rem;
		}

		.uni-table-td {
			font-size: 1rem;
		}

		/deep/ .u-tabs__wrapper__nav__item__text {
			font-size: 1.2rem;
		}
	}

	.tableContent {
		height: 120rpx;
		overflow-y: auto;
	}
	.td-select {
		image {
			display: inline-block;
			height: 30.019rpx;
			width: 37.523rpx;
			margin-left: 6%;
		}
	}

	.td-handle {
		display: flex;
		justify-content: space-evenly;
	}

	.fixed-button {
		width: 100%;
		height: 10%;
		position: fixed;
		z-index: 999;
		bottom: 0;
		display: flex;
		align-items: center;
		background: #FFFFFF;
		box-shadow: 0px -4px 12px 0px rgba(0, 0, 0, 0.3);

		.back {
			width: 30%;
			height: 90%;
			border-radius: 7.505rpx;
			box-sizing: border-box;
			/* 中性色/输入框边框DD */
		}

		.submit {
			width: 70%;
			height: 90%;
			border-radius: 7.505rpx;
			box-sizing: border-box;
		}

		button {
			height: 100%;
			width: 100%;
			font-size: 1.5rem;
			font-weight: bold;
		}
	}
</style>
